<template>
  <div>
    <div class="panel">
      <div class="panel-header">
        {{ $route.params.actId ? '编辑活动' : $route.meta.title }}
      </div>
      <i-form
        ref="form"
        :items="formItems"
        :model="form"
        :rules="rules"
        :label-width="200"
        label-position="left"
        v-if="formVisible"
      >
        <template slot="actStart">
          <el-form-item label="开始时间" prop="actStart" class="is-required">
            <date-picker
              ref="actStart"
              type="datetime"
              v-model="actStart"
              format="YYYY-MM-DD HH:mm"
              placeholder="请选择开始时间"
              :disabled-date="disabledActStartDate"
              :time-picker-options="actStartTime"
              @change="handleActStartChange"
              @pick="handleActStartPick"
              @clear="handleActStartClear"
              :renderInputText="renderActStartInputText"
            >
            </date-picker>
          </el-form-item>
        </template>
        <template slot="actEnd">
          <el-form-item label="结束时间" prop="actEnd" class="is-required">
            <date-picker
              ref="actEnd"
              type="datetime"
              v-model="actEnd"
              format="YYYY-MM-DD HH:mm"
              placeholder="请选择结束时间"
              :disabled-date="disabledActEndDate"
              :time-picker-options="actEndTime"
              @change="handleActEndChange"
              @pick="handleActEndPick"
              @clear="handleActEndClear"
              :renderInputText="renderActEndInputText"
            ></date-picker>
          </el-form-item>
        </template>
        <template slot="voucher">
          <div class="line">
            <span v-if="form.budgetType === 0" class="line-label"
              >优惠券金额：</span
            >
            <span v-if="form.budgetType === 1" class="line-label"
              >优惠券随机金额：</span
            >
            <el-form-item
              v-if="form.budgetType === 0 || form.budgetType === 1"
              prop="randomOne"
              class="line-item"
              ref="randomOne"
            >
              <el-input v-model="form.randomOne"></el-input>
            </el-form-item>
            <span v-if="form.budgetType === 1">—</span>
            <el-form-item
              v-if="form.budgetType === 1"
              prop="randomTwo"
              class="line-item"
              ref="randomTwo"
            >
              <el-input v-model="form.randomTwo"></el-input>
            </el-form-item>
          </div>
        </template>
        <template slot="treeTranfer">
          <el-form-item
            prop="tree"
            :class="roleType === 'ADMIN' ? '' : 'is-required'"
            :label="roleType === 'ADMIN' ? '不参与此活动的代理商' : '活动站点'"
          >
            <el-col :span="24">
              <TreeTransfer
                ref="treeTransfer"
                :title-left="roleType === 'ADMIN' ? '可选代理商' : '可选择电站'"
                :title-right="
                  roleType === 'ADMIN' ? '已选代理商 ' : '已选择电站'
                "
                :data_left="dataLeft"
                :data_right="dataRight"
                :lazy="false"
                :showFilter="showFilter"
                @listenLeftTreeInfoEvent="bindLeftTreeInfoEvent"
                @listenRightTreeInfoEvent="bindRightTreeInfoEvent"
                :type="transferType"
              >
              </TreeTransfer>
            </el-col>
          </el-form-item>
        </template>
        <template slot="backTime">
          <el-form-item label="优惠券赔偿机制" prop="backTime">
            <div class="line">
              <span>当预付费电站发生：</span>
              <el-input v-model.number="form.backTime" :max="60"></el-input>
              <span
                >分钟内的异常结束充电订单时，自动赔偿用户剩余金额的优惠券</span
              >
              <el-button
                size="small"
                type="primary"
                @click="handleSetDefault('backTime')"
                >设置默认值</el-button
              >
            </div>
          </el-form-item>
        </template>
        <template slot="chargingLimit">
          <el-form-item label="充电时长卡获得机制" prop="chargingLimit">
            <div class="line">
              <span>当新用户充电时间达到:</span>
              <el-input v-model.number="form.chargingLimit"></el-input>
              <span
                >分钟,新、老用户会获得对应的{{
                  form.type == 2 ? '时长卡' : '和能量'
                }}</span
              >
              <el-button @click="handleSetDefault('chargingLimit')"
                >设置默认值</el-button
              >
            </div>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel-btn-wrapper">
      <el-button type="success" @click="handleSubmit">确认</el-button>
      <el-button type="warning" @click="handleReset">重置</el-button>
    </div>
  </div>
</template>
<script>
import Big from 'big.js'
import dayjs from 'dayjs'
import { cloneDeep } from 'lodash'
import DatePicker from 'vue2-datepicker'
import 'vue2-datepicker/index.css'
import 'vue2-datepicker/locale/zh-cn'
import TreeTransfer from '@/components/TreeTransfer'
import {
  actStation,
  createAct,
  activityDetail,
  selectMerchant,
  updateAct,
} from '@/api/activity'
import { typeMap } from '@/utils/format'
import formValidate from '@/utils/validate'
const isNum = /^(([1-9][0-9]*)|(([0]\.[1-9]|[0]\.[0-9][1-9]|[1-9][0-9]*\.\d{1,2})))$/
export default {
  name: 'ActivityAdd',
  components: { TreeTransfer, DatePicker },
  data() {
    return {
      dataLeft: [],
      dataRight: [],
      showFilter: true,
      transferType: '',
      dateType: null,
      type: this.$route.params.actId ? 'edit' : 'add',
      actStart: '',
      actEnd: '',
      detail: null,
      form: {},
      originalDataLeft: [],
      originalDataRight: [],
      actStartTime: {
        start: '00:00',
        step: '00:05',
        end: '23:55',
      },
      actEndTime: {
        start: '00:00',
        step: '00:05',
        end: '23:55',
      },
      formItems: [
        {
          label: '活动名称',
          placeholder: '',
          type: 'text',
          value: 'actName',
          required: true,
          maxlength: 30,
          showWordLimit: true,
        },
        {
          slot: 'actStart',
        },
        {
          slot: 'actEnd',
        },
        {
          label: '活动类型',
          type: 'radio',
          value: 'actType',
          required: true,
          options: [],
        },
        {
          label: '折扣率(%)',
          type: 'text',
          value: 'actDiscountRate',
          placeholder: '如输入10代表打1折，输入100代表不打折',
          required: true,
          ifRender: () => {
            return this.form.actType === 0
          },
        },
        {
          label: '活动预算(元)', //后台给的单位是分
          type: 'text',
          value: 'actBudgetMoney',
          placeholder: '预算发放完毕活动会提前结束',
          ifRender: () => {
            return this.form.actType === 1
          },
        },
        {
          label: '活动预算(份)',
          type: 'text',
          value: 'actBudgetNum',
          placeholder: '预算发放完毕活动会提前结束',
          ifRender: () => {
            return this.form.actType === 2 || this.form.actType === 3
          },
        },
        {
          label: '优惠券金额(元)',
          type: 'radio',
          value: 'budgetType',
          options: typeMap.radioOptions([], 'budgetType'),
          required: true,
          change: this.handleBudgetTypeChange,
          ifRender: () => {
            return this.form.actType === 1
          },
        },
        {
          slot: 'voucher',
          ifRender: () => {
            return this.form.actType === 1
          },
        },
        {
          label: '活动时长(小时/人)',
          type: 'text',
          value: 'initialTime',
          ifRender: () => {
            return this.form.actType === 2
          },
        },
        {
          label: '和能量数量(点/人)',
          type: 'text',
          value: 'energyAmount',
          ifRender: () => {
            return this.form.actType === 3
          },
        },
        {
          label: '优惠券有效期(天)',
          type: 'text',
          value: 'sustainedDay',
          ifRender: () => {
            const index = this.formItems.findIndex((item) => {
              return item.value === 'sustainedDay'
            })
            this.formItems[index].label =
              (this.form.actType === 1
                ? '优惠券'
                : this.form.actType === 2
                ? '时长卡'
                : '和能量') + '有效期(天)'
            this.formItems[index].placeholder =
              this.form.actType === 1
                ? ''
                : '有效时间从用户领取时开始计算，最多360天'
            return (
              this.form.actType === 1 ||
              this.form.actType === 2 ||
              this.form.actType === 3
            )
          },
        },
        {
          label: ' 参与此次活动商户类型',
          type: 'radio',
          value: 'joinType',
          options: typeMap.radioOptions([], 'joinType'),
          change: this.handlejoinTypeChange,
          required: true,
          ifRender: () => {
            return (
              (this.form.actType === 2 || this.form.actType === 3) &&
              this.roleType === 'ADMIN'
            )
          },
        },
        {
          label: '领取方式',
          type: 'select',
          value: 'obtainType',
          options: typeMap.selectOptions([], 'obtainType'),
          required: true,
          ifRender: () => {
            return (
              this.form.actType === 1 ||
              this.form.actType === 2 ||
              this.form.actType === 3
            )
          },
        },
        {
          label: '用户范围',
          type: 'select',
          value: 'userRange',
          placeholder: '请选择使用范围',
          options: [],
          required: true,
          ifRender: () => {
            return (
              (this.form.actType === 1 ||
                this.form.actType === 2 ||
                this.form.actType === 3) &&
              this.form.obtainType === 1
            )
          },
        },
        {
          label: '使用范围',
          type: 'select',
          value: 'applyRange',
          placeholder: '请选择使用范围',
          required: true,
          options: typeMap.selectOptions([], 'applyRange'),
          ifRender: () => {
            return this.form.actType === 0 || this.form.actType === 1
          },
        },
        {
          slot: 'backTime',
          ifRender: () => {
            return this.form.actType === 1
          },
        },
        {
          slot: 'chargingLimit',
          ifRender: () => {
            return (
              (this.form.actType === 2 || this.form.actType === 3) &&
              this.form.obtainType === 0
            )
          },
        },
        {
          slot: 'treeTranfer',
        },
      ],
      rules: {
        actDiscountRate: [
          {
            validator: formValidate('validateDiscount'),
            trigger: ['change', 'blur'],
          },
        ],
        tree: [
          {
            validator: (rule, value, callback) => {
              if (this.dataRight.length === 0 && this.roleType !== 'ADMIN') {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: 'blur',
          },
        ],
        actStart: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.actStart) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        actEnd: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.actEnd) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        actBudgetMoney: [
          {
            required: true,
            message: '该项为必填项',
            trigger: ['change', 'blur'],
          },
          {
            validator: (rule, value, callback) => {
              let randomOne =
                this.form.randomOne && value
                  ? Big(value).mod(Big(this.form.randomOne))
                  : null
              let randomTwo =
                this.form.randomTwo && value
                  ? Big(value).mod(Big(this.form.randomTwo))
                  : null
              if (!/^[1-9]{1}[0-9]{0,6}$/.test(value)) {
                return callback(
                  new Error('只能输入大于零整数,最大预算不能超过9999999')
                )
              } else if (
                randomOne &&
                randomTwo &&
                (parseFloat(randomOne) || parseFloat(randomTwo))
              ) {
                return callback(new Error('活动预算和两个随机优惠金额必须整除'))
              } else if (randomOne && parseFloat(randomOne)) {
                return callback(new Error('活动预算和定额优惠金额必须整除'))
              } else {
                return callback()
              }
            },
          },
        ],
        randomOne: [
          {
            required: true,
            message: '该项为必填项',
          },
          {
            validator: (rule, value, callback) => {
              if (!isNum.test(this.form.randomOne)) {
                return callback(new Error('优惠金额大于0且最多两位小数'))
              } else if (
                this.form.randomTwo &&
                parseFloat(this.form.randomTwo) <=
                  parseFloat(this.form.randomOne)
              ) {
                return callback(new Error('结束金额不能小于等于起始金额'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        randomTwo: [
          {
            required: true,
            message: '该项为必填项',
            trigger: ['change', 'blur'],
          },
          {
            validator: (rule, value, callback) => {
              if (!isNum.test(this.form.randomTwo) && this.form.budgetType) {
                return callback(new Error('优惠金额大于0且最多两位小数'))
              } else if (
                this.form.randomOne &&
                parseFloat(this.form.randomTwo) <=
                  parseFloat(this.form.randomOne)
              ) {
                return callback(new Error('结束金额不能小于等于起始金额'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        sustainedDay: [
          {
            required: true,
            message: '该项为必填项',
          },
          {
            validator: (rule, value, callback) => {
              if (
                !/^[1-9]{1}[0-9]{0,6}$/.test(value) &&
                this.form.actType === 1
              ) {
                return callback(
                  new Error('只能输入大于零整数,有效期不能超过9999999')
                )
              } else if (
                (!/^([1-9]{1}\d*)$/.test(value) || value > 360) &&
                (this.form.actType === 2 || this.form.actType === 3)
              ) {
                return callback(
                  new Error('只能输入大于零整数,有效期不能超过360天')
                )
              } else {
                return callback()
              }
            },
            trigger: 'change',
          },
        ],
        backTime: [
          {
            required: true,
            message: '该项为必填项',
          },
          {
            validator: (rule, value, callback) => {
              if (!/^[1-9]{1}[0-9]*$/.test(value) || value > 60) {
                return callback(
                  new Error('只能输入大于零整数,赔偿时间不能大于60分钟')
                )
              } else {
                return callback()
              }
            },
            trigger: 'change',
          },
        ],
        chargingLimit: [
          {
            required: true,
            message: '该项为必填项',
          },
          {
            validator: (rule, value, callback) => {
              if (!/^\d*$/.test(value) || value > 9999 || value < 2) {
                return callback(new Error('充电时长必须为2-9999之间的整数'))
              } else {
                return callback()
              }
            },
            trigger: 'change',
          },
        ],
        actBudgetNum: [
          {
            required: true,
            message: '该项为必填项',
          },
          {
            validator: (rule, value, callback) => {
              if (!/^[1-9]{1}\d*$/.test(value) || value > 999999) {
                return callback(
                  new Error('只能输入大于零整数,最大预算不能超过999999')
                )
              } else {
                return callback()
              }
            },
            trigger: 'change',
          },
        ],
        initialTime: [
          {
            required: true,
            message: '该项为必填项',
          },
          {
            validator: (rule, value, callback) => {
              if (!/^([0]|[1-9]{1}\d*)$/.test(value) || value > 3000) {
                return callback(
                  new Error('只能输入非负整数,最大时长不能超过3000小时')
                )
              } else {
                return callback()
              }
            },
            trigger: 'change',
          },
        ],
        energyAmount: [
          {
            required: true,
            message: '该项为必填项',
          },
          {
            validator: (rule, value, callback) => {
              if (!/^([0]|[1-9]{1}\d*)$/.test(value) || value > 99999) {
                return callback(
                  new Error('只能输入非负整数,最大和能量数量不能超过99999点')
                )
              } else {
                return callback()
              }
            },
            trigger: 'change',
          },
        ],
      },
    }
  },
  watch: {
    'form.actType': {
      async handler(val, oldVal) {
        if (val !== oldVal && oldVal !== undefined) {
          this.form = {
            actType: val,
            actName: this.form.actName,
            actStart: this.form.actStart,
            actEnd: this.form.actEnd,
          }
          if (this.roleType === 'ADMIN') this.$set(this.form, 'joinType', 0) //超管下看传自运营还是非自运营代理商
          let data =
            this.roleType === 'ADMIN'
              ? await selectMerchant({ joinType: this.form.joinType })
              : await actStation({ actType: this.form.actType })
          this.dataLeft =
            this.roleType === 'ADMIN'
              ? this._handleMerchantDataLeft(data)
              : this._handleStationDataLeft(data, 'provinceName', 1)
          this.dataRight = []
          if (val === 1) {
            //优惠券活动下设置参数
            this.$set(this.form, 'budgetType', 0)
            this.$set(this.form, 'randomOne', '')
            this.$set(this.form, 'randomTwo', '')
          }
          this.$nextTick(() => {
            this.$refs.form.clearValidate()
          })
        }
      },
    },
    'form.actStart': {
      handler(val, oldVal) {
        if (val !== oldVal) {
          this.$refs.form && this.$refs.form.validateField('actStart')
        }
      },
    },
    'form.actEnd': {
      handler(val, oldVal) {
        if (val !== oldVal) {
          this.$refs.form && this.$refs.form.validateField('actEnd')
        }
      },
    },
    'form.randomOne': {
      handler(val) {
        this.$refs.form &&
          this.form.actBudgetMoney &&
          isNum.test(val) &&
          this.$refs.form.validateField('actBudgetMoney')
      },
    },
    'form.randomTwo': {
      handler(val) {
        this.$refs.form &&
          this.form.actBudgetMoney &&
          isNum.test(val) &&
          this.$refs.form.validateField('actBudgetMoney')
      },
    },
  },
  methods: {
    handleBudgetTypeChange() {
      this.$set(this.form, 'randomOne', '')
      this.$set(this.form, 'randomTwo', '')
      this.$nextTick(() => {
        this.$refs.randomOne && this.$refs.randomOne.clearValidate()
        this.$refs.randomTwo && this.$refs.randomTwo.clearValidate()
      })
    },
    async handlejoinTypeChange() {
      let data = await selectMerchant({ joinType: this.form.joinType })
      this.dataLeft = this._handleMerchantDataLeft(data)
      this.dataRight = []
    },
    disabledActStartDate(date) {
      return (
        date < new Date().setHours(0, 0, 0, 0) ||
        date > new Date(this.form.actEnd).setHours(0, 0, 0, 0)
      )
    },
    disabledActEndDate(date) {
      return (
        date < new Date(this.form.actStart).setHours(0, 0, 0, 0) ||
        date < new Date().setHours(0, 0, 0, 0)
      )
    },
    handleActStartChange(val, type) {
      this.actStartateType = type
    },
    handleActStartPick(date) {
      let flag = date > new Date()
      this.actStartTime.start = flag
        ? '00:00'
        : new Date().getHours() +
          ':' +
          Math.ceil(new Date().getMinutes() / 5) * 5
      if (this.form.actEnd) {
        if (date < new Date(this.form.actEnd).setHours(0, 0, 0, 0)) {
          this.actStartTime.end = '23:55'
        } else {
          date = new Date(
            new Date(this.form.actEnd).setMinutes(
              new Date(this.form.actEnd).getMinutes() - 5
            )
          )
          this.actStartTime.end = date.getHours() + ':' + date.getMinutes()
        }
      }
    },
    handleActStartClear() {
      this.form.actStart = ''
    },
    renderActStartInputText(val) {
      if (this.actStartateType === 'time') {
        this.form.actStart = Date.parse(val)
        return dayjs(this.form.actStart).format('YYYY-MM-DD HH:mm')
      } else {
        this.form.actStart = this.form.actStart
          ? dayjs(this.form.actStart).valueOf()
          : undefined
        return this.form.actStart
          ? dayjs(this.form.actStart).format('YYYY-MM-DD HH:mm')
          : undefined
      }
    },
    renderActEndInputText(val) {
      if (this.actEndDateType === 'time') {
        this.form.actEnd = Date.parse(val)
        return dayjs(this.form.actEnd).format('YYYY-MM-DD HH:mm')
      } else {
        this.form.actEnd = this.form.actEnd
          ? dayjs(this.form.actEnd).valueOf()
          : undefined
        return this.form.actEnd
          ? dayjs(this.form.actEnd).format('YYYY-MM-DD HH:mm')
          : undefined
      }
    },
    handleActEndChange(val, type) {
      this.actEndDateType = type
    },
    handleActEndPick(date) {
      if (!this.form.actStart) {
        this.actEndTime.start =
          date > new Date()
            ? '00:00'
            : new Date().getHours() +
              ':' +
              Math.ceil(new Date().getMinutes() / 5) * 5
      } else {
        if (date > new Date(this.form.actStart)) {
          this.actEndTime.start = '00:00'
        } else {
          date = new Date(
            new Date(this.form.actStart).setMinutes(
              new Date(this.form.actStart).getMinutes() + 5
            )
          )
          this.actEndTime.start = date.getHours() + ':' + date.getMinutes()
        }
      }
    },
    handleActEndClear() {
      this.form.actEnd = ''
    },
    bindRightTreeInfoEvent(data) {
      this.dataRight = data
      this.$refs.form.validateField('tree')
    },
    bindLeftTreeInfoEvent(data) {
      this.dataLeft = data
    },
    handleReset() {
      this.form =
        this.type === 'add'
          ? { actType: this.roleType === 'ADMIN' ? 2 : 0 }
          : { ...this.detail }
      this.dataLeft = cloneDeep(this.originalDataLeft)
      this.dataRight = cloneDeep(this.originalDataRight)
      this.$nextTick(() => {
        this.$refs.treeTransfer.filterNode('from')
      })
    },
    handleSetDefault(key) {
      const valueMap = {
        backTime: 5,
        chargingLimit: 30,
      }
      this.$set(this.form, key, valueMap[key])
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        if (this.roleType === 'ADMIN') {
          this.form.excludeUserIds = this.dataRight
            .map((item) => item.id)
            .join(',')
        } else {
          this.form.stationIds = this.dataRight.map((item) => item.id).join(',')
        }
        //元转成分
        const params = Object.assign(
          {},
          this.form,
          this.form.randomOne && { randomOne: this.form.randomOne * 100 },
          this.form.randomTwo && { randomTwo: this.form.randomTwo * 100 },
          this.form.actBudgetMoney && {
            actBudgetMoney: this.form.actBudgetMoney * 100,
          },
          this.form.sustainedDay && {
            sustainedDay: parseInt(this.form.sustainedDay),
          },
          this.form.actBudgetNum && {
            actBudgetNum: parseInt(this.form.actBudgetNum),
          },
          this.form.initialTime && {
            initialTime: parseInt(this.form.initialTime),
          },
          this.form.energyAmount && {
            energyAmount: parseInt(this.form.energyAmount), //是否需要*100？
          },
          this.$route.params.actId && {
            actId: parseInt(this.$route.params.actId),
            id: parseInt(this.$route.params.actId),
          }
        )
        !params.randomOne && delete params.randomOne
        !params.randomTwo && delete params.randomTwo
        const handler = {
          add: {
            fn: createAct,
            message: '创建活动成功',
          },
          edit: {
            fn: updateAct,
            message: '编辑活动成功',
          },
        }
        handler[this.type].fn(params).then(() => {
          this.$message({
            type: 'success',
            message: handler[this.type].message,
          })
          this.$router.push('/activity/list')
        })
      })
    },
    //@params level:表示层级
    _handleStationDataLeft(
      arr,
      name,
      parentId,
      parentIndex,
      parentName,
      grandparentName
    ) {
      let tmpArr = []
      arr.forEach((item, index) => {
        let tmpItem = {
          id: item.id,
          name: item[name],
          leaf: name === 'stationName',
          visible: true,
          parent: parentId,
          index: parentIndex ? `${parentIndex}-${index}` : `${index}`,
          parentName: parentName,
          grandparentName: grandparentName,
        }
        if (name === 'provinceName' && item.citys && item.citys.length)
          tmpItem.children = this._handleStationDataLeft(
            item.citys,
            'cityName',
            item.id,
            tmpItem.index,
            item[name]
          )
        if (name === 'cityName' && item.stations && item.stations.length)
          tmpItem.children = this._handleStationDataLeft(
            item.stations,
            'stationName',
            item.id,
            tmpItem.index,
            item[name],
            parentName
          )
        if (
          name === 'stationName' &&
          this.$route.params.actId &&
          (this.detail.stationNames || []).filter(
            (station) => station.stationId === item.id
          ).length
        )
          //编辑状态下数据回填
          this.dataRight.push({
            name: grandparentName + '/' + parentName + '/' + item[name],
            id: item.id,
            visible: true,
            index: tmpItem.index,
          })
        tmpArr.push(tmpItem)
      })
      this.originalDataRight = cloneDeep(this.dataRight)
      return tmpArr
    },
    _handleMerchantDataLeft(data) {
      let tempArr = []
      if (Array.isArray(data)) {
        data.forEach((item) => {
          let tmpItem = {
            name: item.userName,
            id: item.id,
            leaf: true,
            visible: true,
          }
          if (
            this.$route.params.actId &&
            (this.detail.excludeUserNames || []).filter(
              (user) => user.userId === item.id
            ).length
          ) {
            //编辑状态下数据回填
            this.dataRight.push({
              name: item.userName,
              id: item.id,
              leaf: true,
              visible: true,
            })
            tmpItem.visible = false
          }
          tempArr.push(tmpItem)
        })
      }
      this.originalDataRight = cloneDeep(this.dataRight)
      return tempArr
    },
    _handleStationDataRight() {
      for (let node of this.dataRight) {
        let indexArr = node.index.split('-')
        this.dataLeft[indexArr[0]].visible = false
        if (indexArr[1])
          this.dataLeft[indexArr[0]].children[indexArr[1]].visible = false
        if (indexArr[2])
          this.dataLeft[indexArr[0]].children[indexArr[1]].children[
            indexArr[2]
          ].visible = false
      }
      this.$nextTick(() => {
        this.$refs.treeTransfer.filterNode('from')
      })
    },
    _handleMerchantDataRight() {
      this.$nextTick(() => {
        this.$refs.treeTransfer.filterNode('from')
      })
    },
  },
  computed: {
    roleType() {
      return this.$store.getters.roleType
    },
    formVisible() {
      return (
        (this.$route.params.actId && this.detail) || !this.$route.params.actId
      )
    },
  },
  async created() {
    const indexOne = this.formItems.findIndex((item) => {
      return item.value === 'actType'
    })
    const indexTwo = this.formItems.findIndex((item) => {
      return item.value === 'userRange'
    })
    this.formItems[indexOne].options =
      this.roleType === 'ADMIN'
        ? typeMap.radioOptions(['0', '1'], 'actType')
        : typeMap.radioOptions([], 'actType')
    this.formItems[indexTwo].options =
      this.roleType === 'ADMIN'
        ? typeMap.selectOptions([], 'userRange')
        : typeMap.selectOptions(['2', '3', '4'], 'userRange')
    if (this.$route.params.actId) {
      this.detail = await activityDetail({ actId: this.$route.params.actId })
      if (this.detail.actBudgetMoney) this.detail.actBudgetMoney /= 100
      if (this.detail.voucherMoney) {
        let voucherMoneyArr = this.detail.voucherMoney.split(',')
        voucherMoneyArr[0]
          ? (this.detail.randomOne = voucherMoneyArr[0] / 100)
          : null
        voucherMoneyArr[1]
          ? (this.detail.randomTwo = voucherMoneyArr[1] / 100)
          : null
      }
      this.form = { ...this.form, ...this.detail }
    } else {
      this.$set(this.form, 'actType', this.roleType === 'ADMIN' ? 2 : 0)
      this.roleType === 'ADMIN' && this.$set(this.form, 'joinType', 0)
    }
    this.transferType = this.roleType === 'ADMIN' ? 'common' : 'station'
    let data =
      this.roleType === 'ADMIN'
        ? await selectMerchant({ joinType: this.form.joinType })
        : await actStation({ actType: this.form.actType })
    this.dataLeft =
      this.roleType === 'ADMIN'
        ? this._handleMerchantDataLeft(data)
        : this._handleStationDataLeft(data, 'provinceName', 1)
    if (this.$route.params.actId) {
      this.roleType === 'ADMIN'
        ? this._handleMerchantDataRight()
        : this._handleStationDataRight()
    }
    this.originalDataLeft = cloneDeep(this.dataLeft)
  },
}
</script>
<style lang="scss" scoped>
.line {
  display: flex;
  .el-input {
    width: 25%;
    min-width: 220px;
  }
  .el-button {
    margin-left: 10px;
    margin-top: -10px;
  }
  .line-label {
    margin-left: 200px;
    font-size: 14px;
    line-height: 40px;
  }
  .line-item {
    &::v-deep .el-form-item__content {
      margin-left: 0 !important;
      width: 100%;
    }
    .el-input {
      min-width: 150px;
      width: 100%;
    }
  }
}
.i-form {
  padding: 0 40px;
  &::v-deep .el-form-item__content {
    width: 50%;
  }
  &::v-deep .el-form-item.is-error .el-transfer-panel__body .el-input__inner,
  .el-form-item.is-error .el-textarea__inner {
    border-color: #d9d9d9;
  }
  &::v-deep .el-form-item.is-error .el-transfer-panel {
    border-color: #ff4d4f;
  }
  &::v-deep .el-form-item.is-error .mx-input {
    border-color: #ff4d4f;
  }
}
</style>
